//
//  HttpProxy.m
//  HiveApp
//
//  Created by Zhu Arashmen on 9/17/12.
//  Copyright (c) 2012 HiveView. All rights reserved.
//

#import "HttpProxy.h"
#import "FocusParser.h"

@interface HttpProxy(){
    BaseParser<ParseExecutor> *_parser;
    NSString *responseReceiver;

}

@end

@implementation HttpProxy
@synthesize responseCode,responseContent,responseErrorMessage;

-(void)dealloc{
    [super dealloc];
    //need to release memory
    [_parser release];
    
    
}

-(void)executeWithString:(NSString *)url :(NSString *)receiver:(BaseParser<ParseExecutor>*)parser{

    [self executeWithURL:[NSURL URLWithString:url] :receiver:parser];
    
}
-(void)executeWithURL:(NSURL *)url :(NSString *)receiver:(BaseParser<ParseExecutor>*)parser{
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    responseReceiver = receiver;
    _parser = [parser retain];
    [parser release];

    [request setDelegate:self];
    [request startAsynchronous];

}

-(void)requestStarted:(ASIHTTPRequest *)request{
    
}

-(void)requestFinished:(ASIHTTPRequest *)request{
//    request.responseData
//    request.responseString
//    request.responseStatusCode
//    request.responseStatusMessage
//    接口参数类导致的错误在此可以处理
//    正确的返回也在此处理

    NSDictionary *items = [request.responseString objectFromJSONString];
    NSDictionary *statusDict = [items objectForKey:@"status"];
    int code = [[statusDict objectForKey:@"code"] intValue];
    if(code == 0){
        NSLog(@"class=%@",NSStringFromClass([[items objectForKey:@"result"] class]));
        NSDictionary *itemsResult = [items objectForKey:@"result"];
        NSArray *array = [_parser excuteToObjects:itemsResult];
        [[NSNotificationCenter defaultCenter] postNotificationName:responseReceiver object:array];
    }
    [self release];
}

-(void)requestFailed:(ASIHTTPRequest *)request{
//    接口服务器不稳定
//    网络不稳定
//    重大错误均在此方法内执行
    [[NSNotificationCenter defaultCenter] postNotificationName:responseReceiver object:nil];
    [self release];
}

@end
